package com.example.covid19.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Component
public class Face {
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();

    public static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if (fileMap != null && fileMap.size() > 0) {
            Iterator fileIter = fileMap.entrySet().iterator();
            while (fileIter.hasNext()) {
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try {
            if (code == 200) {
                ins = conne.getInputStream();
            } else {
                ins = conne.getErrorStream();
            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while ((len = ins.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }

    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }

    private static String encode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8");
    }

    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }

    @RequestMapping("/upload")
    public String upLoad(@RequestPart("file") MultipartFile multipartFile){
        log.info("文件上传开始");
        log.info("文件{}",multipartFile.getOriginalFilename());
        String str;
        if (!multipartFile.isEmpty()){
            try {
                //上传的文件需要保存的路径和文件名称，路径需要存在，否则报错
                multipartFile.transferTo(new File("D:/"+multipartFile.getOriginalFilename()));
                str="D:/"+multipartFile.getOriginalFilename();

            } catch (IllegalStateException | IOException e){
                e.printStackTrace();
                return "上传失败";
            }
        } else {
            return "请上传文件";
        }
        return str;
    }
    @RequestMapping("/upload")
    public String ppload(@RequestPart("file") MultipartFile multipartFile){
        log.info("文件上传开始");
        log.info("文件{}",multipartFile.getOriginalFilename());
        String str;
        if (!multipartFile.isEmpty()){
            try {
                //上传的文件需要保存的路径和文件名称，路径需要存在，否则报错
                multipartFile.transferTo(new File("F:/FaceResp/"+System.currentTimeMillis()+multipartFile.getOriginalFilename()));
                str="D:/"+multipartFile.getOriginalFilename();

            } catch (IllegalStateException | IOException e){
                e.printStackTrace();
                return "上传失败";
            }
        } else {
            return "请上传文件";
        }
        return str;
    }
    public String getter(String str) {
        JSONObject jsonObject = new JSONObject();
        jsonObject = JSON.parseObject(str);
        JSONArray array = jsonObject.getJSONArray("faces");
        String str2;
        JSONObject jo = array.getJSONObject(0);
        String   TransType = jo.getString("face_rectangle");
        String   CheckType = jo.getString("face_token");
        String   Value = jo.getString("attributes");
        String   ActualValue = jo.getString("glass");
//
//        System.out.println("---------------------1"+TransType);
//        System.out.println("---------------------2"+CheckType);
//        System.out.println("---------------------3"+Value);
//        System.out.println("---------------------4"+ActualValue);

        return CheckType;
    }
    public List<String> getcc(String str4) {
        JSONObject jsonObject = new JSONObject();
        jsonObject = JSON.parseObject(str4);
        JSONArray array = jsonObject.getJSONArray("results");
        String str2;
//    for (int i = 0; i < array.size(); i++) {
        JSONObject jo = array.getJSONObject(0);
        String   TransType = jo.getString("confidence");
        String   CheckType = jo.getString("face_token");
        String   Value = jo.getString("user_id");

//        System.out.println("---------------------1"+TransType);
//        System.out.println("---------------------2"+CheckType);
//        System.out.println("---------------------3"+Value);
        List<String> list = new ArrayList<>();
        list.add(TransType);
        list.add(CheckType);
        return list;
//    }

    }
}
